import type { AxiosInstance, AxiosRequestConfig } from 'axios'
import axios from 'axios'
import tokenService from './token.service'
import { useNotifyStore } from '@/store/notify.store'
import { pinia } from '@/modules/pinia'

function httpClient(baseApi: string | null = null): AxiosInstance {
  const client = axios.create({
    baseURL: baseApi ?? `${import.meta.env.VITE_API_URL}/`,
    headers: {
      'Content-Type': 'application/json',
    },
  })

  client.interceptors.request.use(
    (config: AxiosRequestConfig) => {
      const token = tokenService.getLocalAccessToken()
      if (token && config.headers)
        config.headers.Authorization = `Bearer ${token}`

      return config
    },
    (error) => {
      return Promise.reject(error)
    },
  )

  client.interceptors.response.use(
    (response) => {
      return response
    },
    (error) => {
      // 只在非404错误或者有具体错误消息时显示通知
      if (error.response && error.response.statusText && error.response.status !== 404) {
        useNotifyStore(pinia).error(error.response.statusText)
      } else if (error.message && !error.response) {
        // 处理网络错误等没有response的情况
        useNotifyStore(pinia).error(error.message)
      }

      return Promise.reject(error)
    },
  )
  return client
}

export default httpClient
